<?php

namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','headpic','sex'
    ];



    /**
     * 模型的事件映射。
     *
     * @var array
     */
    /*protected $dispatchesEvents = [
        'saved' => UserSaved::class,
        'deleted' => UserDeleted::class,
    ];*/

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function owns($related){
        return $this->id == $related->user_id;
    }

    public function chats()
    {
        return $this->hasMany('App\Models\Chat');
    }

    public function rooms()
    {
        return $this->belongsToMany('App\Models\Room','user_room','user_id','room_id');
    }
    public function canJoinRoom($roomId){
        $user_in_room = DB::table('user_room')->where('room_id',$roomId)->where('user_id',$this->id)->get();
        if(count($user_in_room)>0){
            return true;
        }else{
            return false;
        }
    }
    public function joinRoom($roomId){
        $id = DB::table('user_room')->insertGetId(['user_id'=>$this->id,'room_id'=>$roomId]);
        return $id;
    }
    public function asyncRoom(){

    }

}
